#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
#include "global.h"

/* 
sdl2 只用一个 160x120 大小的瓷砖组来制作一个 1280x960 大小的图像
*/

//全部面积大小
// 由于渲染的大小不再是屏幕的大小，必须有一组单独的常量来定义渲染的大小。
const int LEVEL_WIDTH = 1280;
const int LEVEL_HEIGHT = 960;

//当前框大小
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

//瓷砖常数
const int TILE_WIDTH = 80;
const int TILE_HEIGHT = 80;
const int TOTAL_TILES = 192;
const int TOTAL_TILE_SPRITES = 12;

//不同的瓷砖精灵
const int TILE_RED = 0;
const int TILE_GREEN = 1;
const int TILE_BLUE = 2;
const int TILE_CENTER = 3;
const int TILE_TOP = 4;
const int TILE_TOPRIGHT = 5;
const int TILE_RIGHT = 6;
const int TILE_BOTTOMRIGHT = 7;
const int TILE_BOTTOM = 8;
const int TILE_BOTTOMLEFT = 9;
const int TILE_LEFT = 10;
const int TILE_TOPLEFT = 11;

TTF_Font* gFont = nullptr; 
// 渲染的窗口
SDL_Window * gWindow = nullptr;
//The window renderer
SDL_Renderer* gRenderer = nullptr;

//粒子数量
const int TOTAL_PARTICLES = 20;

// 封装SDL_Texture
//Texture wrapper class
class LTexture
{
    public:
        //Initializes variables
        LTexture();

        //Deallocates memory
        ~LTexture();

        //Loads image at specified path
        bool loadFromFile( std::string path );

        #if defined(SDL_TTF_MAJOR_VERSION)
        /*
        如果头文件不包含 SDL_ttf.h，编译器就会忽略它。它检查是否定义了 SDL_TTF_MAJOR_VERSION 宏。
        与 #include 一样，#if 也是用于与编译器对话的宏。在本例中，它表示如果 SDL_ttf 未定义，则忽略这段代码
        */
        //Creates image from font string
        // SDL_ttf 的工作方式是根据字体和颜色创建新图像。对于纹理类来说，这意味着将从 SDL_ttf 渲染的文本而不是文件中加载图像
        bool loadFromRenderedText( std::string textureText, SDL_Color textColor );
        #endif

        //Deallocates texture
        void free();

        //设置调制颜色，接收红、绿、蓝三色分量
        void setColor( Uint8 red, Uint8 green, Uint8 blue );

        //设置纹理混合  它将控制纹理的混合方式。为了使混合正常工作，必须设置纹理的混合模式
        void setBlendMode( SDL_BlendMode blending );

        //设置纹理的 alpha 透明度
        void setAlpha( Uint8 alpha );

        //Renders texture at given point
        /*接受一个矩形参数，用来定义我们要渲染的纹理部分。我们给它一个默认参数 nullptr，以防我们想要渲染整个纹理
          接受旋转角度、纹理旋转点和 SDL 翻转枚举值，同样也给出了参数的默认值，以备在不旋转或翻转的情况下渲染纹理。
        */
        void render( int x, int y, SDL_Rect* clip = nullptr, double angle = 0.0, SDL_Point* center = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE );

        //Gets image dimensions
        int getWidth();
        int getHeight();

    private:
        //实际渲染的纹理
        SDL_Texture* mTexture;

        //图像的宽和高
        int mWidth;
        int mHeight;
};

LTexture::LTexture()
{
    //Initialize
    mTexture = nullptr;
    mWidth = 0;
    mHeight = 0;
}

LTexture::~LTexture()
{
    //Deallocate
    free();
}

void LTexture::setColor( Uint8 red, Uint8 green, Uint8 blue )
{
    //纹理颜色调制
    /*
    DL_SetTextureColorMod 接受 Uint8 作为颜色组件的参数。Uint8 只是一个无符号的 8 位整数。这意味着它的范围从 0 到 255。
    128 大约介于 0 和 255 之间，因此当您将绿色调制为 128 时，纹理上任何像素的绿色分量都会减半。
    红色和蓝色方格不会受到影响，因为它们没有绿色，但绿色的亮度会减半，白色则会变成浅洋红色（洋红色为红色 255、绿色 0、蓝色 255）。
    颜色调制只是将一种颜色乘以整个纹理的一种方法
    */
    SDL_SetTextureColorMod( mTexture, red, green, blue );
}

#if defined(SDL_TTF_MAJOR_VERSION)
bool LTexture::loadFromRenderedText( std::string textureText, SDL_Color textColor )
{
    ////先取消原有纹理的渲染
    free();

    //Render text surface
    /*
    根据字体创建要渲染的纹理。该函数接收要渲染的文本字符串和要用来渲染它的颜色。在此之后，该函数的工作原理与从文件加载相似，
    只不过这次使用的是由 SDL_ttf 创建的 SDL_Surface，而不是文件
    使用 TTF_RenderText_Solid 加载一个曲面。函数会根据给出的字体、文本和颜色创建一个纯色曲面。如果曲面创建成功，
    就会像之前从文件加载曲面一样创建纹理。创建纹理后，我们就可以像渲染其他纹理一样对其进行渲染。
    */
    if(gFont == nullptr)
    {
        std::cout << "gFont nullptr" << std::endl;
    }
    SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
    if( textSurface == nullptr )
    {
        std::cout << "Unable to render text surface! SDL_ttf Error:" << TTF_GetError() << std::endl;
    }
    else
    {
        //Create texture from surface pixels
        mTexture = SDL_CreateTextureFromSurface( gRenderer, textSurface );
        if( mTexture == nullptr )
        {
            std::cout << "Unable to create texture from rendered text! SDL Error:" << SDL_GetError() << std::endl;
        }
        else
        {
            //Get image dimensions
            mWidth = textSurface->w;
            mHeight = textSurface->h;
        }

        //Get rid of old surface
        SDL_FreeSurface( textSurface );
    }
    
    //Return success
    return mTexture != NULL;
}
#endif

bool LTexture::loadFromFile( std::string path )
{
    //先取消原有纹理的渲染
    free();

    //The final texture
    SDL_Texture* newTexture = nullptr;

    //Load image at specified path
    SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
    if( loadedSurface == nullptr )
    {
        std::cout<< "Unable to load image "<< path.c_str() << "!, SDL_image Error: " << IMG_GetError() << std::endl;
    }
    else
    {
        /*  使用 SDL_SetColorKey 对图像进行去除背景。第一个参数是我们要进行去除背景处理的表面，第二个参数是我们是否要启用去除背景处理，
        最后一个参数是我们要进行去除背景处理的像素(图像中哪种颜色要去除)
            从 RGB 颜色创建像素的方法是使用 SDL_MapRGB。第一个参数是我们想要的像素格式(SDL_PixelFormat 结构)。幸运的是，载入的曲面中有一个成员变量可以获取该格式。
         最后三个变量是要映射的颜色的红、绿、蓝分量。
         青色 0，255，255
         黑色 0，0，0
         白色 255，255，255
        */
        SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xff, 0xff ) );

        //Create texture from surface pixels
        newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface );
        if( newTexture == nullptr )
        {
            std::cout << "Unable to create texture from " << path.c_str() << "! SDL Error: " << SDL_GetError() << std::endl;
        }
        else
        {
            //Get image dimensions
            mWidth = loadedSurface->w;
            mHeight = loadedSurface->h;
        }

        //清楚旧纹理加载
        SDL_FreeSurface( loadedSurface );
    }

    //Return success
    mTexture = newTexture;
    return mTexture != nullptr;
}

void LTexture::free()
{
    //Free texture if it exists
    if( mTexture != nullptr )
    {
        SDL_DestroyTexture( mTexture );
        mTexture = nullptr;
        mWidth = 0;
        mHeight = 0;
    }
}

void LTexture::render( int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip )
{
    //设置渲染区域并渲染到屏幕
    SDL_Rect renderQuad = { x, y, mWidth, mHeight };
    /* 在特定位置渲染纹理时，需要指定一个目标矩形，该矩形可设置 x/y 位置和宽度/高度。在不知道原始图像尺寸的情况下，我们无法指定宽度/高度。
    因此，当我们渲染纹理时，我们会创建一个包含位置参数和成员宽度/高度的矩形，并将此矩形传递给 SDL_RenderCopy
    */

    //Set clip rendering dimensions
    if( clip != nullptr )
    {
        renderQuad.w = clip->w;
        renderQuad.h = clip->h;
    }
    /*
    在剪辑时，如果使用的是剪辑矩形的尺寸而不是纹理的尺寸，我们将把目标矩形（此处称为 renderQuad）的宽度/高度设置为剪辑矩形的尺寸。
    我们要将剪辑矩形作为源矩形传递给 SDL_RenderCopy。源矩形定义了要渲染纹理的哪一部分。当源矩形为空时，将渲染整个纹理。
    */

    //Render to screen
    // SDL_RenderCopy( gRenderer, mTexture, clip, &renderQuad );
    //Render to screen 该函数的工作原理与原始的 SDL_RenderCopy 相同，但增加了用于旋转和翻转的参数
    SDL_RenderCopyEx( gRenderer, mTexture, clip, &renderQuad, angle, center, flip );
}

int LTexture::getWidth()
{
    return mWidth;
}

int LTexture::getHeight()
{
    return mHeight;
}

void LTexture::setBlendMode( SDL_BlendMode blending )
{
    //Set blending function
    // SDL_SetTextureBlendMode 允许启用混合模式
    SDL_SetTextureBlendMode( mTexture, blending );
}
        
void LTexture::setAlpha( Uint8 alpha )
{
    //Modulate texture alpha
    // SDL_SetTextureAlphaMod 则允许设置整个纹理的 Alpha 值
    SDL_SetTextureAlphaMod( mTexture, alpha );
}

LTexture gDotTexture;
LTexture gTileTexture;
SDL_Rect gTileClips[TOTAL_TILE_SPRITES];

//Render text r,g,b,a
SDL_Color textColor = { 0, 0xff, 0xff, 0xff };

//瓷砖类
class Tile
{
    public:
        //Initializes position and type
        Tile( int x, int y, int tileType );

        //Shows the tile
        void render( SDL_Rect& camera );

        //Get the tile type
        int getType();

        //获取碰撞盒
        SDL_Rect getBox();

    private:
        //The attributes of the tile
        SDL_Rect mBox;

        //The tile type
        int mType;
};

Tile::Tile( int x, int y, int tileType )
{
    //Get the offsets
    mBox.x = x;
    mBox.y = y;

    //Set the collision box
    mBox.w = TILE_WIDTH;
    mBox.h = TILE_HEIGHT;

    //Get the tile type
    mType = tileType;
}

void Tile::render( SDL_Rect& camera )
{
    //If the tile is on screen
    if( checkCollision( camera, mBox ) )
    {
        //Show the tile
        gTileTexture.render( mBox.x - camera.x, mBox.y - camera.y, &gTileClips[ mType ] );
    }
}

int Tile::getType()
{
    return mType;
}

SDL_Rect Tile::getBox()
{
    return mBox;
}

//点类，可以在屏幕上移动
class Dot
{
    public:
        //点的尺寸
        static const int DOT_WIDTH = 20;
        static const int DOT_HEIGHT = 20;

        //点的最大轴速度
        static const int DOT_VEL = 5;

        //Initializes the variables
        Dot(int x, int y);

        Dot();

        ~Dot();

        //按下按键并调整点的速度
        void handleEvent( SDL_Event& e );

        //移动点并检查碰撞 移动函数将接收一个碰撞方框组，这样就可以对两组碰撞方框进行检查
        void move(std::vector<SDL_Rect>& otherColliders);

        //Moves the dot and checks collision
        void move( SDL_Rect& square, Circle& circle );

        void move();

        //移动圆点并检查与瓷砖的碰撞
        void move( Tile *tiles[] );

        //Centers the camera over the dot
        void setCamera( SDL_Rect& camera );

        //Shows the dot on the screen
        void render( SDL_Rect& camera );

        //在屏幕上渲染点
        void render();

        // 渲染屏幕上相对于当前框的点
        // 点必须相对于当前框进行渲染，因此它的渲染函数接收了当前框的位置
        void render( int camX, int camY );

        //获取每个点的碰撞方框组
        std::vector<SDL_Rect>& getColliders();

         //Gets collision circle
        Circle& getCollider();

        //Position accessors
        int getPosX();
        int getPosY();

    private:
        //The particles
        // Particle* particles[ TOTAL_PARTICLES ];

        //Shows the particles
        void renderParticles();

        //Collision box of the dot
        SDL_Rect mBox;

        //点的坐标
        int mPosX, mPosY;

        //点的速度
        int mVelX, mVelY;

        //点的碰撞方框组
        std::vector<SDL_Rect> mColliders;

        //Dot's collision circle
        Circle mCollider;

        //根据点的坐标移动碰撞框组
        void shiftColliders();
};

int Dot::getPosX()
{
    return mPosX;
}

int Dot::getPosY()
{
    return mPosY;
}

Dot::Dot(int x, int y)
{
    //Initialize the offsets
    mPosX = x;
    mPosY = y;

    //Set collision circle size
    mCollider.r = DOT_WIDTH / 2;

    //Initialize the velocity
    mVelX = 0;
    mVelY = 0;

    //Move collider relative to the circle
    shiftColliders();
}

void Dot::handleEvent( SDL_Event& e )
{
    //If a key was pressed
    // 如果每次按右键时都增加 x 位置，那么就必须反复按右键才能保持移动。而通过设置速度，只需按一次键即可
    //要检查按键重复次数是否为 0，因为按键重复次数默认是启用的，如果按住一个键，它会报告多次按键。这意味着必须检查按键是否是第一次按下，因为只关心按键第一次按下的时间
    if( e.type == SDL_KEYDOWN && e.key.repeat == 0 )
    {
        std::cout << "key press" << std::endl;
        //Adjust the velocity
        switch( e.key.keysym.sym )
        {
            // 如果一个物体以每帧 10 像素的速度向右移动，它的速度就是 10。如果它以每帧 10 像素的速度向左移动，则速度为-10。如果点的速度是 10，这意味着 10 帧后它将移动 100 个像素
            case SDLK_UP: 
                if(mVelY > -DOT_VEL)
                {
                    mVelY -= DOT_VEL; 
                }
                break;
            case SDLK_DOWN: 
                if(mVelY < DOT_VEL)
                {
                    mVelY += DOT_VEL; 
                }
                break;
            case SDLK_LEFT: 
                if(mVelX > -DOT_VEL)
                {
                    mVelX -= DOT_VEL;
                }
                break;
            case SDLK_RIGHT: 
                if(mVelX < DOT_VEL)
                {
                    mVelX += DOT_VEL;
                }
                break;
        }
    }

    //If a key was released
    // else if( e.type == SDL_KEYUP && e.key.repeat == 0 )
    // {
    //     std::cout << "key release" << std::endl;
    //     //Adjust the velocity
    //     switch( e.key.keysym.sym )
    //     {
    //         case SDLK_UP: mVelY += DOT_VEL; break;
    //         case SDLK_DOWN: mVelY -= DOT_VEL; break;
    //         case SDLK_LEFT: mVelX += DOT_VEL; break;
    //         case SDLK_RIGHT: mVelX -= DOT_VEL; break;
    //     }
    // }
}

Dot::Dot()
{
    //Initialize the collision box
    mBox.x = 0;
    mBox.y = 0;
	mBox.w = DOT_WIDTH;
	mBox.h = DOT_HEIGHT;

    //Initialize the velocity
    mVelX = 0;
    mVelY = 0;

    //Initialize particles
    // for( int i = 0; i < TOTAL_PARTICLES; ++i )
    // {
    //     particles[ i ] = new Particle( mPosX, mPosY );
    // }
}

Dot::~Dot()
{
    //Delete particles
    // for( int i = 0; i < TOTAL_PARTICLES; ++i )
    // {
    //     delete particles[ i ];
    // }
}

// 每帧移动圆点时调用的函数
void Dot::move(std::vector<SDL_Rect>& otherColliders)
{
    //Move the dot left or right
    mPosX += mVelX;
    shiftColliders();
    std::cout << "dot move" << ", mPosX=" << mPosX << std::endl;

    /*
    沿 x 轴移动圆点，同时也改变碰撞器的位置。每当改变点的位置时，碰撞器的位置也必须跟着改变。
    然后，检查点是否离开屏幕或撞到墙壁。如果有，就将点沿 x 轴向后移动。最后，再对 Y 轴上的运动做一次这样的检查。
    */
    //若点相撞或过于偏左或偏右
    if( ( mPosX < 0 ) || ( mPosX + DOT_WIDTH > SCREEN_WIDTH ) || checkCollision( this->mColliders, otherColliders ) )
    {
        //Move back
        mPosX -= mVelX;
        shiftColliders();
    }

    //Move the dot up or down
    mPosY += mVelY;
    shiftColliders();
    std::cout << "dot move" << ", mPosY=" << mPosY << std::endl;

    //若点相撞或过于偏上或偏下
    if( ( mPosY < 0 ) || ( mPosY + DOT_HEIGHT > SCREEN_HEIGHT ) || checkCollision( this->mColliders, otherColliders )  )
    {
        //Move back
        mPosY -= mVelY;
        shiftColliders();
    }
}

void Dot::move( SDL_Rect& square, Circle& circle )
{
    //Move the dot left or right
    mPosX += mVelX;
    shiftColliders();
    std::cout << "dot move" << ", mPosX=" << mPosX << ",mVelX=" << mVelX << std::endl;
    bool temp1 = checkCollision( mCollider, square );
    bool temp2 = checkCollision( mCollider, circle );
    std::cout << "dot move" << ", temp1=" << temp1 << ",temp2=" << temp2 << std::endl;

    //If the dot collided or went too far to the left or right
    if( ( mPosX - mCollider.r < 0 ) || ( mPosX + mCollider.r > SCREEN_WIDTH ) || checkCollision( mCollider, square ) || checkCollision( mCollider, circle ) )
    {
        //Move back
        mPosX -= mVelX;
        shiftColliders();
    }

    //Move the dot up or down
    mPosY += mVelY;
    shiftColliders();
    std::cout << "dot move" << ", mPosY=" << mPosY << ",mVelY=" << mVelY << std::endl;

    //If the dot collided or went too far up or down
    if( ( mPosY - mCollider.r < 0 ) || ( mPosY + mCollider.r > SCREEN_HEIGHT ) || checkCollision( mCollider, square ) || checkCollision( mCollider, circle ) )
    {
        //Move back
        mPosY -= mVelY;
        shiftColliders();
    }
}

void Dot::move()
{
    //Move the dot left or right
    mPosX += mVelX;
    std::cout << "dot move" << ", mPosX=" << mPosX << ",mVelX=" << mVelX << std::endl;

    // 要检查圆点是否移出了水平面，而不是检查圆点是否移出了屏幕，因为屏幕会在水平面周围移动
    //If the dot went too far to the left or right
    if( ( mPosX < 0 ) || ( mPosX + DOT_WIDTH > SCREEN_WIDTH) )
    {
        //Move back
        mPosX -= mVelX;
    }

    //Move the dot up or down
    mPosY += mVelY;
    std::cout << "dot move" << ", mPosY=" << mPosY << ",mVelY=" << mVelY << std::endl;

    //If the dot went too far up or down
    if( ( mPosY < 0 ) || ( mPosY + DOT_HEIGHT > SCREEN_HEIGHT ) )
    {
        //Move back
        mPosY -= mVelY;
    }
}

void Dot::shiftColliders()
{
    //行偏移量，每行碰状况高度不一致，所以需要变量记录当前行碰状况的y值
    // int r = 0;

    //查看点的碰撞框组
    // for( int set = 0; set < mColliders.size(); ++set )
    // {
    //     //将碰撞框居中
    //     mColliders[ set ].x = mPosX + ( DOT_WIDTH - mColliders[ set ].w ) / 2;

    //     //根据行偏移量设置碰撞框
    //     mColliders[ set ].y = mPosY + r;

    //     //将行偏移量向下移动碰撞框的高度
    //     r += mColliders[ set ].h;
    // }
    this->mCollider.x = this->mPosX;
    this->mCollider.y = this->mPosY;
}

std::vector<SDL_Rect>& Dot::getColliders()
{
    return mColliders;
}

Circle& Dot::getCollider()
{
    return mCollider;
}

void Dot::render()
{
     //Show the dot
    gDotTexture.render( mPosX, mPosY );

    //Show particles on top of dot
    renderParticles();
}

// 将对象渲染到屏幕上时
void Dot::render( int camX, int camY )
{
    //Show the dot relative to the camera
    gDotTexture.render( mPosX - camX, mPosY - camY );
}

void Dot::renderParticles()
{
    //Go through particles
    // for( int i = 0; i < TOTAL_PARTICLES; ++i )
    // {
    //     //粒子渲染函数会检查是否有已死亡的粒子，并替换它们
    //     if( particles[ i ]->isDead() )
    //     {
    //         delete particles[ i ]; // 堆上的对象，用delete回收
    //         particles[ i ] = new Particle( mPosX, mPosY );
    //     }
    // }

    // //替换掉死粒子后，将所有当前粒子渲染到屏幕上
    // for( int i = 0; i < TOTAL_PARTICLES; ++i )
    // {
    //     particles[ i ]->render();
    // }
}

//根据瓷片数据检查碰撞盒
// 检查瓷砖组中每一面墙的碰撞框，当需要检查整个瓷砖组中的点时，就会用到这个函数
bool touchesWall( SDL_Rect box, Tile* tiles[] )
{
     //Go through the tiles
    for( int i = 0; i < TOTAL_TILES; ++i )
    {
        //If the tile is a wall type tile
        /*
        touchesWall 函数会检查给定碰撞框中是否存在 TILE_CENTER、TILE_TOP、TILE_TOPRIGHT、TILE_RIGHT、TILE_BOTTOMRIGHT、TILE_BOTTOM、
        TILE_BOTTOMLEFT、TILE_LEFT 和 TILE_TOPLEFT 类型的瓷砖，这些瓷砖都是墙砖,它们的编号是紧挨着的，介于 TILE_CENTER 和 TILE_TOPLEFT 之间
        如果给定的碰撞框与任何墙面砖发生碰撞，此函数将返回 true
        */
        if( ( tiles[ i ]->getType() >= TILE_CENTER ) && ( tiles[ i ]->getType() <= TILE_TOPLEFT ) )
        {
            //If the collision box touches the wall tile
            if( checkCollision( box, tiles[ i ]->getBox() ) )
            {
                return true;
            }
        }
    }

    //If no wall tiles were touched
    return false;
}

//根据地图加载设置瓷片
bool setTiles( Tile *tiles[] )
{
    //Success flag
    bool tilesLoaded = true;

    //定义了放置瓷砖的位置。当载入更多瓷砖时，将从左到右、从上到下移动 x/y 位置
    int x = 0, y = 0;

    //Open the map
    std::ifstream map( "lazy.map" );

    //If the map couldn't be loaded
    if( map.fail() )
    {
        std::cout << "Unable to load map file!" << std::endl;
        tilesLoaded = false;
    }
    else
    {
        //Initialize the tiles
        //将一个数字读入 tileType 变量，然后检查读取是否失败。如果读取失败，中止。如果没有，检查磁贴类型数字是否有效。如果有效，创建一个给定类型的新磁贴；如果无效，打印错误并停止加载磁贴
        for( int i = 0; i < TOTAL_TILES; ++i )
        {
            //Determines what kind of tile will be made
            int tileType = -1;

            //Read tile from map file
            map >> tileType;

            //If the was a problem in reading the map
            if( map.fail() )
            {
                //Stop loading map
                std::cout << "Error loading map: Unexpected end of file!" << std::endl;
                tilesLoaded = false;
                break;
            }

            //If the number is a valid tile number
            if( ( tileType >= 0 ) && ( tileType < TOTAL_TILE_SPRITES ) )
            {
                tiles[ i ] = new Tile( x, y, tileType );
            }
            //If we don't recognize the tile type
            else
            {
                //Stop loading map
                std::cout << "Error loading map: Invalid tile type at " << i << std::endl;
                tilesLoaded = false;
                break;
            }

             //Move to next tile spot
             //装入一块瓷砖后，移动到右边的文字瓷砖位置。如果到达了一行磁贴的末尾，则向下移动到下一行
            x += TILE_WIDTH;

            //If we've gone too far
            if( x >= LEVEL_WIDTH )
            {
                //Move back
                x = 0;

                //Move to the next row
                y += TILE_HEIGHT;
            }
        }

        //Clip the sprite sheet
        if( tilesLoaded )
        {
            gTileClips[ TILE_RED ].x = 0;
            gTileClips[ TILE_RED ].y = 0;
            gTileClips[ TILE_RED ].w = TILE_WIDTH;
            gTileClips[ TILE_RED ].h = TILE_HEIGHT;

            gTileClips[ TILE_GREEN ].x = 0;
            gTileClips[ TILE_GREEN ].y = 80;
            gTileClips[ TILE_GREEN ].w = TILE_WIDTH;
            gTileClips[ TILE_GREEN ].h = TILE_HEIGHT;

            gTileClips[ TILE_BLUE ].x = 0;
            gTileClips[ TILE_BLUE ].y = 160;
            gTileClips[ TILE_BLUE ].w = TILE_WIDTH;
            gTileClips[ TILE_BLUE ].h = TILE_HEIGHT;

            gTileClips[ TILE_TOPLEFT ].x = 80;
            gTileClips[ TILE_TOPLEFT ].y = 0;
            gTileClips[ TILE_TOPLEFT ].w = TILE_WIDTH;
            gTileClips[ TILE_TOPLEFT ].h = TILE_HEIGHT;

            gTileClips[ TILE_LEFT ].x = 80;
            gTileClips[ TILE_LEFT ].y = 80;
            gTileClips[ TILE_LEFT ].w = TILE_WIDTH;
            gTileClips[ TILE_LEFT ].h = TILE_HEIGHT;

            gTileClips[ TILE_BOTTOMLEFT ].x = 80;
            gTileClips[ TILE_BOTTOMLEFT ].y = 160;
            gTileClips[ TILE_BOTTOMLEFT ].w = TILE_WIDTH;
            gTileClips[ TILE_BOTTOMLEFT ].h = TILE_HEIGHT;

            gTileClips[ TILE_TOP ].x = 160;
            gTileClips[ TILE_TOP ].y = 0;
            gTileClips[ TILE_TOP ].w = TILE_WIDTH;
            gTileClips[ TILE_TOP ].h = TILE_HEIGHT;

            gTileClips[ TILE_CENTER ].x = 160;
            gTileClips[ TILE_CENTER ].y = 80;
            gTileClips[ TILE_CENTER ].w = TILE_WIDTH;
            gTileClips[ TILE_CENTER ].h = TILE_HEIGHT;

            gTileClips[ TILE_BOTTOM ].x = 160;
            gTileClips[ TILE_BOTTOM ].y = 160;
            gTileClips[ TILE_BOTTOM ].w = TILE_WIDTH;
            gTileClips[ TILE_BOTTOM ].h = TILE_HEIGHT;

            gTileClips[ TILE_TOPRIGHT ].x = 240;
            gTileClips[ TILE_TOPRIGHT ].y = 0;
            gTileClips[ TILE_TOPRIGHT ].w = TILE_WIDTH;
            gTileClips[ TILE_TOPRIGHT ].h = TILE_HEIGHT;

            gTileClips[ TILE_RIGHT ].x = 240;
            gTileClips[ TILE_RIGHT ].y = 80;
            gTileClips[ TILE_RIGHT ].w = TILE_WIDTH;
            gTileClips[ TILE_RIGHT ].h = TILE_HEIGHT;

            gTileClips[ TILE_BOTTOMRIGHT ].x = 240;
            gTileClips[ TILE_BOTTOMRIGHT ].y = 160;
            gTileClips[ TILE_BOTTOMRIGHT ].w = TILE_WIDTH;
            gTileClips[ TILE_BOTTOMRIGHT ].h = TILE_HEIGHT;
        }
    }

    //Close the file
    map.close();

    //If the map was loaded fine
    return tilesLoaded;
}

// 当移动圆点时，检查它是否偏离水平线或碰到墙砖
void Dot::move( Tile *tiles[] )
{
    //Move the dot left or right
    mBox.x += mVelX;

    //If the dot went too far to the left or right or touched a wall
    if( ( mBox.x < 0 ) || ( mBox.x + DOT_WIDTH > LEVEL_WIDTH ) || touchesWall( mBox, tiles ) )
    {
        //move back
        // mBox.x -= mVelX;
        mVelX = -mVelX;
    }

    //Move the dot up or down
    mBox.y += mVelY;

    //If the dot went too far up or down or touched a wall
    if( ( mBox.y < 0 ) || ( mBox.y + DOT_HEIGHT > LEVEL_HEIGHT ) || touchesWall( mBox, tiles ) )
    {
        //move back
        // mBox.y -= mVelY;
        mVelY = -mVelY;
    }
}

void Dot::setCamera( SDL_Rect& camera )
{
    //Center the camera over the dot
    camera.x = ( mBox.x + DOT_WIDTH / 2 ) - SCREEN_WIDTH / 2;
    camera.y = ( mBox.y + DOT_HEIGHT / 2 ) - SCREEN_HEIGHT / 2;

    //Keep the camera in bounds
    if( camera.x < 0 )
    { 
        camera.x = 0;
    }
    if( camera.y < 0 )
    {
        camera.y = 0;
    }
    if( camera.x > LEVEL_WIDTH - camera.w )
    {
        camera.x = LEVEL_WIDTH - camera.w;
    }
    if( camera.y > LEVEL_HEIGHT - camera.h )
    {
        camera.y = LEVEL_HEIGHT - camera.h;
    }
}

void Dot::render( SDL_Rect& camera )
{
    //Show the dot
    gDotTexture.render( mBox.x - camera.x, mBox.y - camera.y );
}

bool init()
{
     //Initialization flag
    bool success = true;

    //Initialize SDL
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        std::cout << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl;
        success = false;
    }
    else
    {
        //Set texture filtering to linear
        if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
        {
            std::cout << "Warning: Linear texture filtering not enabled!" << std::endl;
        }
        //Create window
        gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
        if( gWindow == nullptr )
        {
            std:: cout << "Window could not be created! SDL_Error: " << SDL_GetError() << std::endl;
            success = false;
        }
        else
        {
            //Create renderer for window
            // gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED );
            //为窗口创建垂直同步渲染器
            /*
            垂直同步,VSync 可以让渲染与显示器在垂直刷新时的更新同步进行。在本教程中，它将确保动画的运行速度不会太快。
            大多数显示器的运行速度约为每秒 60 帧，这也是我们的假设。如果你的显示器刷新率不同，这就能解释为什么动画运行得过快或过慢
            */
            gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
            if( gRenderer == nullptr )
            {
                std::cout << "Renderer could not be created! SDL Error:" << SDL_GetError() << std::endl;
                success = false;
            }
            else
            {
                //Initialize renderer color
                SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );

                //Initialize PNG loading
                int imgFlags = IMG_INIT_PNG;
                if( !( IMG_Init( imgFlags ) & imgFlags ) )
                {
                    std::cout << "SDL_image could not initialize! SDL_image Error:" << IMG_GetError() << std::endl;
                    success = false;
                }

                // //Initialize SDL_ttf
                // if( TTF_Init() == -1 )
                // {
                //     std::cout << "SDL_ttf could not initialize! SDL_ttf Error:" << TTF_GetError() << std::endl;
                //     success = false;
                // }
            }

        }
    }

    return success;
}

bool loadMedia(Tile* tiles[])
{
    //Loading success flag
    bool success = true;

    ///Load dot texture
    if( !gDotTexture.loadFromFile( "dot.bmp" ) )
    {
        std::cout << "Failed to load dot texture!" << std::endl;
        success = false;
    }

    //Load tile texture
    if( !gTileTexture.loadFromFile( "tiles.png" ) )
    {
        std::cout << "Failed to load tile set texture!" << std::endl;
        success = false;
    }

    //Load tile map
    if( !setTiles( tiles ) )
    {
        std::cout << "Failed to load tile set!" << std::endl;
        success = false;
    }

    return success;
}

void close(Tile* tiles[])
{
    for( int i = 0; i < TOTAL_TILES; ++i )
	{
		 if( tiles[ i ] != NULL )
		 {
			delete tiles[ i ];
			tiles[ i ] = NULL;
		 }
	}
    //Destroy windows
    SDL_DestroyWindow(gWindow);
    gWindow = nullptr;
    SDL_DestroyRenderer(gRenderer);
    gRenderer = nullptr;

    gDotTexture.free();
    gTileTexture.free();

    //Quit SDL subsystems
    // TTF_Quit();
    // Mix_Quit();
    IMG_Quit();
    SDL_Quit();
}

int main( int argc, char* args[] )
{
    //Start up SDL and create window
    if( !init() )
    {
        std::cout << "Failed to initialize!" << std::endl;
    }
    else
    {
        //The level tiles
        Tile* tileSet[ TOTAL_TILES ];
        //Load media
        if( !loadMedia( tileSet ) )
        {
            std::cout << "Failed to load media!" << std::endl;
        }
        else
        {
            //Hack to get window to stay up
            SDL_Event e; 
            bool quit = false; 
            //The dot that will be moving around on the screen
            Dot dot;
            //Level camera
			SDL_Rect camera = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };

            //While application is running
            while( !quit )
            {
                //Handle events on queue
                while( SDL_PollEvent( &e ) != 0 )
                {
                    //User requests quit
                    if( e.type == SDL_QUIT )
                    {
                        quit = true;
                    }
                    //Handle input for the dot
                    dot.handleEvent( e );
                }
                //Move the dot
                //当移动圆点时，传入瓷片集，然后在圆点移动后将摄像头设置在圆点上方。然后渲染瓦片集，最后渲染水平线上的点
                dot.move( tileSet );
                dot.setCamera( camera );

                //Clear screen
                SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
                SDL_RenderClear( gRenderer );

                //Render level
                for( int i = 0; i < TOTAL_TILES; ++i )
                {
                    tileSet[ i ]->render( camera );
                }

                //Render dot
                dot.render( camera );

                //Update screen
                SDL_RenderPresent( gRenderer );
            }
        }
        //Free resources and close SDL
        close(tileSet);
    }

    return 0;
}



